﻿using System.Data;
using System.Web;
using Token.Piker.BLL;
using System.Web.Security;
using System.Web.SessionState;
using Token.Piker.Common;
using Token.Piker.Core.Security;
using Token.Util;
using System;

namespace Token.Piker.Web.AJAX
{
    /// <summary>
    /// UserLogin 的摘要说明
    /// </summary>
    public class UserLogin : BaseAjaxHandler
    {
        class Login
        {
            //登录是否成功
            public string success;
        }

        protected override void Mapping()
        {
            OprationMap["Login"] = "LoginPikerUser";
        }

        protected override void ResponseTemplate(Object data)
        {
            ResponseText = JsonHelper.Serialize(data);
        }

        public void LoginPikerUser()
        {
            try
            {
                Login login = new Login();
                string userName = Context.Request.Params["user"];
                string password = Context.Request.Params["pass"];
                if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
                {
                    return;
                }

                if (CheckLogin(userName, password))
                {
                    login.success = "true";
                }
                else
                {
                    login.success = "false";
                }

                ResponseTemplate(login);
                IsSuccess = true;
            }
            catch
            {
                IsSuccess = false;
            }
        }

        private bool CheckLogin(string username,string password)
        {
            string encodedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(password,"MD5");
            UserBLL userBLL = new UserBLL();
            string strWhere = "UserName = '" + username + "' AND UserPwd = '" + encodedPassword + "'";
            DataSet ds = userBLL.GetList(strWhere);
            if (ds.Tables[0].Rows.Count > 0)
            {
                DataRow dr = ds.Tables[0].Rows[0];
                string userId = dr["ID"].ToString();
                string userName = dr["UserName"].ToString();
                HttpSessionState Session = HttpContext.Current.Session;
                Session[GlobalConstants.PIKER_USER_ID] = userId;
                Session[GlobalConstants.PIKER_USER_NAME] = userName;
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}